package com.yc.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.framework.utils.IntUtil;
import com.yc.framework.utils.ObjectUtils;
import com.yc.framework.utils.RedisUtils;
import com.yc.system.dto.RegisterInfo;
import com.yc.system.dto.UserDto;
import com.yc.system.entity.Book;
import com.yc.system.entity.User;
import com.yc.system.entity.UserRole;
import com.yc.system.mapper.UserMapper;
import com.yc.system.mapper.UserRoleMapper;
import com.yc.system.service.IUserService;
import com.yc.framework.baseClass.BaseServiceImpl;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.yc.framework.baseClass.R;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Base64;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 1850140986@qq.com
 * @since 2022-12-03
 */

@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper,User> implements IUserService {

    @Autowired
    public UserMapper userMapper;

    @Value("${file.upload.path}")
    private String path;
    @Value("${file.upload.relativePath}")
    private String relativePath;
    @Autowired
    public RedisUtils redisUtils;
    @Autowired
    public UserRoleMapper userRoleMapper;

    @Value("${jwt.secret}")
    private String secret;

    /**
    * 分页查询实体列表
    * @param model 查询参数
    * @return 查询结果
    */

    @Override
    public R list( User model){
        IPage<User> page = new Page<>(model.getPageNum(),model.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
         initCondition(wrapper);
        setParam(wrapper,model);
         IPage<User> px = page(page,wrapper);
        return R.ok().put("data",px.getRecords()).put("total", px.getTotal());
    }

    @Override
    public R getUserByUserId(int userId) {

        return R.ok().put("userInfo",userMapper.getUserByUserId(userId));
    }

    @Override
    public R changePpictureAddr(int userId, String reqFullFileName) {

                String db_PpictureAddr = userMapper.getPpictureAddrByUserId(userId);
        System.out.println("changePpictureAddr:-----------db_PpictureAddr"+db_PpictureAddr);
                if(db_PpictureAddr.length()>0){
                    String db_1coverPhotoAddr = db_PpictureAddr.replace(relativePath + "/", "");
                    String coverPhotoAddr = db_1coverPhotoAddr.replaceAll("/", "\\\\");
                    System.out.println("coverPhotoAddr:"+coverPhotoAddr);
                    String realPath = null;
                    try {
                        realPath = path + URLDecoder.decode(coverPhotoAddr, "UTF-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                        return R.err().put("message", "文件地址错误" + e.getMessage());
                    }
                    File f = new File(realPath);
                    System.out.println("是否已经存在，需要删除原保存的图片-----------------------------------：" + realPath + f.exists());
                    if (f.delete()) {
                        System.out.println("File deleted successfully------------------------");
                    } else {
                        System.out.println("Failed to delete the file----------------------");
                    }
                }

                int i =userMapper.changePpictureAddr(userId, reqFullFileName);
                return R.ok().put("userId", userId).put("ppictureAddr", reqFullFileName);

    }

    @Override
    @Transactional
    public R register(RegisterInfo registerInfo) {
//        Long userIdByUsername=userMapper.getUserIdByUsername(registerInfo.getUsername());
//        if(userIdByUsername!=null||userIdByUsername!=0){
//            return R.err().put("data","该用户名已被注册！");
//        }

//        Long userIdByEmail=userMapper.getUserByEmail(registerInfo.getEmail());
//        if(userIdByEmail!=null){
//            return R.err().put("data","该邮箱已被注册！（可选用邮箱验证登录）");
//        }
        String test=null;
        try{
            test=redisUtils.get(registerInfo.getEmail()).toString();
        }catch (Exception e){
            return R.err().put("data","验证码过期，请重新发送。");
        }

        if(ObjectUtils.isEmpty(test)){
            return R.err().put("data","验证码过期，请重新发送。");
        }else if(!test.toLowerCase().equals(registerInfo.getTest().toLowerCase())){
            return R.err().put("data","验证码不正确！");
        }

        registerInfo.setPassword(new BCryptPasswordEncoder().encode(registerInfo.getPassword()));
        User user=new User();
//        username,password,phone,email
        user.setPassword(registerInfo.getPassword());
        user.setUsername(registerInfo.getUsername());
        user.setPhone(registerInfo.getPhone());
        user.setEmail(registerInfo.getEmail());
//        int i=userMapper.register(user);
        int i=userMapper.insert(user);
        System.out.println("getUserId"+user.getUserId());
        int j;
        if(registerInfo.getAdmin()){
            j=userRoleMapper.addAdminByUserId(user.getUserId().longValue());
        }else{
            j=userRoleMapper.addUserByUserId(user.getUserId().longValue());
        }

        if(i==1&&j==1){
            return R.ok();
        }else{
            return R.err().put("data","服务器数据库错误");
        }

    }

    @Override
    public R updataByUserInfo(User user) {
        int i = userMapper.updataByUserInfo(user);
        if(i==1){
            return R.ok().put("userInfo",userMapper.getUserByUserId(user.getUserId()));
        }
        return R.err();
    }

    @Override
    public R checkAdminByUserId(Integer userId) {
        int i = userMapper.getAdminByUserId(userId);
        return i==1?R.ok():R.err();
    }


    /**
    * 根据主键删除实体对象，返回值封装成R，若成功则会把要删除的主键计入返回的R
    *
    * @param id 主键
    * @return 删除是否成功
   
    @Override
    public R removeModelById(String id){
        User model=new User();
        model.setId(id);
        return removeModelById(model);
    }
 */
    public  void setParam(QueryWrapper<User> wrapper, User model) {
        if (model == null) {
        return;
        }
       // wrapper.eq("deleted", false);
    }
}
